package com.saris.primego.service.impl;

import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.constant.PasswordConstant;
import com.saris.primego.common.constant.StatusConstant;
import com.saris.primego.common.context.BaseContext;
import com.saris.primego.common.exception.AccountLockedException;
import com.saris.primego.common.exception.AccountNotFoundException;
import com.saris.primego.common.exception.EntityNotFoundException;
import com.saris.primego.common.exception.PasswordErrorException;
import com.saris.primego.common.result.PageResult;
import com.saris.primego.dao.EmployeeRepository;
import com.saris.primego.pojo.dto.EmployeeDTO;
import com.saris.primego.pojo.dto.EmployeeLoginDTO;
import com.saris.primego.pojo.dto.EmployeePageQueryDTO;
import com.saris.primego.pojo.entity.Employee;
import com.saris.primego.service.EmployeeService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeRepository employeeRepository;
    private final ModelMapper modelMapper;

    public EmployeeServiceImpl(EmployeeRepository employeeRepository, ModelMapper modelMapper) {
        this.employeeRepository = employeeRepository;
        this.modelMapper = modelMapper;
    }

    @Override
    public Employee getByUsername(String username) {
        return employeeRepository.findByUsername(username);
    }

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {

        String username = employeeLoginDTO.getUsername();
        // 传入明文密码进行Md5处理 123456 → e10adc3949ba59abbe56e057f20f883e
        String password = DigestUtils.md5DigestAsHex(employeeLoginDTO.getPassword().getBytes());

        //1、根据用户名查询数据库中的数据
        Employee employee = getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public Long addEmployee(EmployeeDTO employeeDTO) {

        log.info("当前线程的Id：{}", Thread.currentThread().threadId());

        Employee employee = modelMapper.map(employeeDTO, Employee.class);

        // 设置账号状态，1为启用，2为禁用
        employee.setStatus(StatusConstant.ENABLE);

        // 设置密码，默认密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        // 设置创建和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 设置创建人Id和修改人Id
        // 从ThreadLocal 读取用户Id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        Employee result = employeeRepository.save(employee);
        log.info("新增员工的Id= {}", result.getId().toString());
        return result.getId() != null ? result.getId() : null;
    }

    @Override
    public PageResult<Employee> pagedQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        String userName = employeePageQueryDTO.getName();
        int page = employeePageQueryDTO.getPage();
        int size = employeePageQueryDTO.getPageSize();

        // 在 Service 中调用
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("updateTime")); // 由于pageNumber 从 0 开始，传入的页码需要-1
        if (userName == null || userName.trim().isEmpty()) {
            Page<Employee> all = employeeRepository.findAll(pageable);
            return new PageResult<>(all.getTotalElements(), all.getContent());
        } else {
            Page<Employee> allByName = employeeRepository.findAllByName(userName, pageable);
            return new PageResult<>(allByName.getTotalElements(), allByName.getContent());
        }

    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Optional<Employee> optionalEmployee = employeeRepository.findById(id);

        optionalEmployee.ifPresent(employee -> {
            if (Objects.equals(employee.getStatus(), StatusConstant.ENABLE)) {
                employee.setStatus(StatusConstant.DISABLE);
            } else {
                employee.setStatus(StatusConstant.ENABLE);
            }

            employee.setUpdateTime(LocalDateTime.now());
            employee.setUpdateUser(BaseContext.getCurrentId());

            employeeRepository.save(employee);
        });

    }

    @Override
    public Employee getById(Long id) {
        return employeeRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(MessageConstant.EMPLOYEE_NOT_FOUND));
    }

    @Transactional
    @Override
    public void update(EmployeeDTO employeeDTO) {
        // 1. 查询现有实体
        Employee employee = employeeRepository.findById(employeeDTO.getId())
                .orElseThrow(() -> new EntityNotFoundException(MessageConstant.EMPLOYEE_NOT_FOUND));

        // 2. 将 DTO 的非空字段映射到实体（跳过 null 值）
        modelMapper.map(employeeDTO, employee);

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
    }
}
